#include "Sound.h"

Sound::Sound(void)
: theSoundEngine(NULL)
, theSound(NULL)
, soundFilename(NULL)
{
}

Sound::~Sound(void)
{
	if (theSound != NULL)
	{
		for (int i=0; i < TOTALSOUND; i++)
		{
			delete theSound[i];
			theSound[i] = NULL;
		}
		theSound = NULL;
	}

	if (soundFilename != NULL)
	{
		delete[] soundFilename;
		soundFilename = NULL;
	}

	if (theSoundEngine != NULL)
	{
		theSoundEngine->drop();
	}
}

bool Sound::Init(void)
{
	// Start the sound engine
	theSoundEngine = createIrrKlangDevice();

	// Error starting up the sound engine
	if (!theSoundEngine)
	{
		cout << "Sound engine cannot be started." << endl;
		return false;
	}

	// Initialise all sound
	theSound = new ISound*[TOTALSOUND];
	soundFilename = new string[TOTALSOUND];

	for (int i=0; i < TOTALSOUND; i++)
	{
		theSound[i] = NULL;
		soundFilename[i] = '\0';
	}

	// MENUS SOUND //
	soundFilename[MENUKEY] = "sound/Button.mp3";
	soundFilename[BACKGROUND] = "sound/Lullaby.mp3";
	soundFilename[SELECT] = "sound/Select.mp3";
	soundFilename[JUMP] = "sound/Jump.mp3";
	soundFilename[CHARATTACK] = "sound/Attack_GreatSword.mp3";
	soundFilename[WALK] = "sound/Walk.mp3";

	return true;
}

// pause sound
bool Sound::Pause(SOUND soundID, bool pause)
{
	// check if sound exist
	if (soundID < 0 || soundID >= TOTALSOUND ) 
	{
		cout << "Sound does not exist." << endl;
		return false;
	}

	// pause sound
	if (theSound[soundID] != NULL )
		theSound[soundID]->setIsPaused( pause );

	return true;
}

bool Sound::Play(SOUND soundID, bool playLooped)
{
	// check if sound exist
	if (soundID < 0 || soundID >= TOTALSOUND ) 
	{
		cout << "Sound does not exist." << endl;
		return false;
	}

	if(theSound[soundID] != NULL)
	{
		// check if sound is finished
		if (theSound[soundID]->isFinished() == true)
		{
			theSound[soundID] = NULL;
		}
		// unpause sound if it is paused
		else if (theSound[soundID]->getIsPaused() == true)
		{
			theSound[soundID]->setIsPaused(false);
		}
	}

	// Play sound
	if(theSound[soundID] == NULL)
	{
		theSound[soundID] = theSoundEngine->play2D(soundFilename[soundID].c_str(), playLooped, true);

		if (soundID == BACKGROUND)
			theSound[soundID]->setVolume(0.4f);

		theSound[soundID]->setIsPaused(false);
	}

	return true;
}

// stop sound
bool Sound::Stop(SOUND soundID)
{
	// check if sound exist
	if (soundID < 0 || soundID >= TOTALSOUND ) 
	{
		cout << "Sound does not exist." << endl;
		return false;
	}

	// stop sound
	theSound[soundID]->stop();

	return true;
}

// stop all sound
void Sound::StopAll(void)
{
	theSoundEngine->stopAllSounds();
}